
// Copyright (C) 2009-2011 Luca Piccioni
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//  
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//  
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Diagnostics;

using Derm.Render;

namespace Derm.Scene
{
	/// <summary>
	/// 
	/// </summary>
	public class AnimationService : RenderKernelService
	{
		#region Constructors

		/// <summary>
		/// 
		/// </summary>
		public AnimationService() : base("Derm.Scene.Animation", ExecutionModel.Context)
		{
			
		}

		#endregion

		#region Animation Management

		/// <summary>
		/// 
		/// </summary>
		/// <param name="ani"></param>
		public void RegisterAnimation(RenderAnimation ani)
		{
			Debug.Assert(ani != null);

			lock(mAnimations) {
				mAnimations.Add(ani);
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="ani"></param>
		public void UnregisterAnimation(RenderAnimation ani)
		{
			
		}

		#endregion

		#region Time Tracking

		/// <summary>
		/// 
		/// </summary>
		public void SetBeginTime()
		{
			// Store time
			mBeginTime = DateTime.Now;
		}

		/// <summary>
		/// Animation begin time.
		/// </summary>
		private DateTime mBeginTime;
		/// <summary>
		/// Last animation time.
		/// </summary>
		private DateTime mLastAnimationTime;

		#endregion

		#region RenderKernel.ContextService Implementation

		/// <summary>
		/// Execute this AnimationService tasks.
		/// </summary>
		/// <param name="ctx">
		/// A <see cref="RenderContext"/>
		/// </param>
		protected override void ThreadExecute(RenderContext ctx)
		{
			DateTime endTime = DateTime.Now;
			TimeSpan aniTime = endTime-mLastAnimationTime;

			// Store last update time
			mLastAnimationTime = endTime;
			// Execute every registered animation
			foreach (RenderAnimation kAni in mAnimations)
				kAni.Animate(aniTime);
			mAnimations.Clear();
		}

		/// <summary>
		/// Service animations.
		/// </summary>
		private List<RenderAnimation> mAnimations = new List<RenderAnimation>();
		
		#endregion
	}
}
